    package com.example.adapter;

    import android.app.Activity;
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.example.db.CommonData;
    import com.example.im.R;
    import com.example.model.Friends;
    import com.example.model.Msg;
    import com.example.model.User;
    import com.example.util.MyUtil;

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Objects;
    import java.util.stream.Collectors;

    import static com.example.db.CommonData.commonData;
    import static com.example.db.CommonData.getDbFriendList;
    import static com.example.util.MyUtil.exeUrlTask;
    import static com.example.util.MyUtil.toast;

    public class ChatListAdapter extends BaseAdapter {
        private final LayoutInflater inflater;
        private final List<Msg> mData;
        private final Context context;

        public ChatListAdapter(Context context, List<Msg> data) {
            inflater = LayoutInflater.from(context);
            this.context = context;
            this.mData = data;
        }

        public ChatListAdapter(LayoutInflater inflater, List<Msg> mData, Context context) {
            this.inflater = inflater;
            this.mData = mData;
            this.context = context;
        }

        // 要绑定的条目的数目
        @Override
        public int getCount() {
            return mData.size();
        }

        // 根据一个索引（位置）获得该位置的对象
        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        // 获取条目的id
        @Override
        public long getItemId(int position) {
            return position;
        }

        // 获取该条目要显示的界面
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ChatListAdapter.ChatHolder holder;
            Msg msg = mData.get(position);
            int loginUserId = CommonData.commonData.getUser().getId();
            // 第一次加载条目时，初始化界面和相应函数
            if (convertView == null) {
                holder = new ChatListAdapter.ChatHolder();
                convertView = inflater.inflate(R.layout.chat_list_item1, parent, false);
                holder.leftMsg = (TextView) convertView.findViewById(R.id.left_tv);
                holder.rightMsg = (TextView) convertView.findViewById(R.id.right_tv);
                convertView.setTag(holder);
            } else {
                holder = (ChatListAdapter.ChatHolder) convertView.getTag();
            }
            holder.leftMsg.setText(msg.getMsg());
            holder.rightMsg.setText(msg.getMsg());
            if (msg.getFid() == loginUserId) {
                // 我收到的消息 隐藏右边
                holder.leftMsg.setVisibility(View.VISIBLE);
                holder.rightMsg.setVisibility(View.GONE);
            } else if (msg.getUid() == loginUserId) {
                // 我发送的消息 隐藏左边
                holder.leftMsg.setVisibility(View.GONE);
                holder.rightMsg.setVisibility(View.VISIBLE);
            }
            return convertView;
        }

        public void flush(Friends friend) {
            //获取消息接口
            exeUrlTask(context,
                    () -> MyUtil.getReqParam("/imChatUserMessage/listFriendMessage",
                            MyUtil.paramMap(Collections.singletonList("friendId"),
                                    Collections.singletonList(friend.getFid()))),
                    res -> ((Activity) context).runOnUiThread(() -> {
                        /* 数组
                   {
        "code": 200,
        "message": null,
        "data": {
            "records": [
                {
                    "id": 1,
                    "fromId": 7,
                    "toId": 6,
                    "content": "晓青最6",
                    "messageStatus": false,
                    "createTime": "2024-01-06 20:27:26",
                    "avatar": null
                }
            ]
            "total": 0,
            "size": 40,
            "current": 1,
            "orders": [],
            "optimizeCountSql": true,
            "hitCount": false,
            "countId": null,
            "maxLimit": null,
            "searchCount": true,
            "pages": 0
        },
        "currentTimeMillis": 1704540257508
    }
                         */
                        JSONObject data = res.getDataObject();
                        JSONArray records = data.getJSONArray("records");
                        List<Msg> dbMsg = CommonData.getDbMsg(commonData.getUser().getName(), friend.getName());
                        for (int i = 0; i < records.size(); i++) {
                            JSONObject json = records.getJSONObject(i);
                            Msg msg = new Msg();
                            msg.setMid(json.getInteger("id"));
                            msg.setUid(json.getInteger("fromId"));
                            msg.setFid(json.getInteger("toId"));
                            msg.setMsg(json.getString("content"));
                            msg.setStatus(json.getBoolean("messageStatus"));
                            msg.setSendTime(json.getDate("createTime"));
                            msg.setType(0);
                            CommonData.addDbMsg(commonData.getLoginUserName(), friend.getName(), msg);
                        }
                        // 保存一下
                        CommonData.writeData(context);
                        mData.clear();
                        mData.addAll(dbMsg);
                        notifyDataSetChanged();

                    }),
                    r -> {
                        mData.clear();
                        mData.addAll(CommonData.getDbMsg(commonData.getUser().getName(), friend.getName()));
                        notifyDataSetChanged();
                    });
        }

        // 新建holder类，对listview进行简单优化
        public static class ChatHolder {
            TextView id;
            TextView leftMsg;
            TextView rightMsg;
        }
    }
